﻿using blackhouse.WebNemo.Business;
using blackhouse.WebNemo.Business.Groups;
using System;
using System.Drawing;
using System.Web;
using System.Web.Script.Serialization;

namespace blackhouse.WebNemo.Web.Controls.ReferenceGallery {
    public class GalleryService : IHttpHandler {

        #region Fields

        HttpRequest request;

        #endregion

        #region IHttpHandler Members

        public bool IsReusable {
            get { return false; }
        }

        public void ProcessRequest(HttpContext context) {
            this.request = context.Request;
            context.Response.ContentType = "text/html";
            JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
            GalleryItem gmo = this.UploadGalleryItem();
            string sGmo = javaScriptSerializer.Serialize(gmo);
            context.Response.Write(sGmo);
        }

        private GalleryItem UploadGalleryItem() {
            
            if(this.request.Files.Count==0) throw new Exception("Brak pliku!");
            HttpPostedFile postedFile = this.request.Files[0];
            Factory factory = Factory.Instance();
            int groupId, refGroupId,refColumnId;
            if(
                !Int32.TryParse(this.request.Form["group"],out groupId)
                ||!Int32.TryParse(this.request.Form["refgroup"],out refGroupId)
                ||!Int32.TryParse(this.request.Form["column"],out refColumnId)
                ) throw new InvalidCastException("Przekazano błędne parametry");
            GalleryController controller = new GalleryController(null, factory.GetGroup(groupId), factory.GetGroup(refGroupId), refColumnId);
            return controller.UploadPhoto(postedFile, new Size(250, 220));
        }

        #endregion

    }
}
